package by.averianov.discounta.webapp.page.create;

import javax.inject.Inject;

import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.CardType;
import by.averianov.discounta.datamodel.Shop;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.BaseLayout;

public class CreateCardType extends BaseLayout {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CreateCardType.class);

	public Long id;
	public String nameCardType;
	
	private PageCreator pageCreator;

	public CreateCardType(CardType cardType, PageCreator pageCreator) {
		super(null);
		this.pageCreator = pageCreator;
		try {
			this.id = cardType.getId(); 
			this.nameCardType = cardType.getNameCardType();
			LOGGER.debug("Shop is changing");
		} catch (Exception e) {
			LOGGER.debug("Shop is creating");
			this.id = null;
		}
	}

	@Inject
	private UserService userService;


	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		final TextField<String> nameCardTypeText = new TextField<String>("nameCardType", Model.of(nameCardType));
		
		Form<?> form = new Form<Void>("cardTypeCreateForm") {
			@Override
			protected void onSubmit() {
				
				PageParameters pageParameters = new PageParameters();
				
		        LOGGER.debug("Set Shop");
		        CardType resultingCardType = new CardType();
		        resultingCardType.setId(id);
		        resultingCardType.setNameCardType(nameCardTypeText.getModelObject().toString());
		        userService.saveOrUpdateCardType(resultingCardType);
				setResponsePage(pageCreator.createPage());
			}
		};		 
		add(form);
		
		form.add(nameCardTypeText);
		form.add(new Label("labelCreateCardType", getLabelCreateCardType(id)));
		form.add(new Label("labelCardTypeIdText", getLabelCardTypeId()));		
		final Label labelCardTypeId = new Label("labelCardTypeId", id);
		form.add(labelCardTypeId);			
		form.add(new Label("labelNameCardType", getLabelNameCardType()));	
		form.add(new Label("labelSave", getButtonSave()));	
		
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
				
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
		
	}

}